import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';

import routes from 'virtual:generated-pages';

const router = createRouter({
  history: createWebHistory(),
  //history: createWebHashHistory(),
  strict: true,
  // createWebHashHistory hash 路由
  // createWebHistory history 路由
  // createMemoryHistory 带缓存 history 路由
  routes: routes as unknown as RouteRecordRaw[],
  scrollBehavior(to, from, savedPosition) {
    return new Promise(resolve => {
      if (savedPosition) {
        return savedPosition;
      } else {
        if (from.meta.saveSrollTop) {
          const top: number = document.documentElement.scrollTop || document.body.scrollTop;
          resolve({ left: 0, top });
        }
      }
    });
  },
});

import { elckerAuthPiniaStore } from '@/store/modules/ElckerAuth';

router.beforeEach((to, from, next) => {
  const formPath = to.fullPath;
  const elckerAuthStore = elckerAuthPiniaStore();
  if (elckerAuthStore.getIsLogin) {
    if (import.meta.env.VITE_PAGE_LOGIN == formPath) {
      next(import.meta.env.VITE_PAGE_HOME + '');
    } else {
      next();
    }
  } else {
    if (import.meta.env.VITE_PAGE_LOGIN == formPath) {
      next();
    } else {
      next(import.meta.env.VITE_PAGE_LOGIN + '');
    }
  }
});

export default router;
